/** 防抖函数 */
function debounce(fn, delay) {
    //  创建一个标记来存放延时器的执行ID
    let timer = null;
    //  返回的函数，就是事件监听要执行的函数
    return function (e) {
        timer && clearTimeout(timer);
        timer = setTimeout(fn.bind(this, arguments), delay);
    };
}

//	遮罩层提示框
function $toast(msg, delay) {
    let o = document.createElement('div');
    o.style.width = '70vw';
    o.style.height = '35vh';
    o.style.position = 'absolute';
    o.style.left = '50%';
    o.style.top = '50%';
    o.style.transform = 'translateX(-50%) translateY(-50%)';
    o.style.zIndex = '999';
    o.style.display = 'flex';
    o.style.justifyContent = 'center';
    o.style.alignItems = 'center';
    o.style.backgroundColor = 'rgba(0,0,0,.3)';
    o.style.color = '#fff';
    o.style.borderRadius = '10vw';
    o.style.boxShadow = '4px 4px 4px 1px rgba(0, 0, 0, 0.39)';
    o.innerText = msg;
    document.body.appendChild(o);

    // 默认delay秒后取消
    let timer = setTimeout(function () {
        o.remove();
    }, delay);

    // 点击该元素后取消
    o.addEventListener('click', function () {
        this.remove();
        clearTimeout(timer);
    });
}

// 转换年月日
function dateHandler(timestamp) {
    let date = new Date(Number(timestamp));
    let year = date.getFullYear();
    let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
    let days = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return `${year}年${month}月${days}日`;
}

// 转换时分
function timeHandler(timestamp) {
    let date = new Date(Number(timestamp));
    let hour = date.getHours().toString().padStart(2, 0);
    let min = date.getMinutes().toString().padStart(2, 0);
    return `${hour}:${min}`;
}

export { debounce, $toast, dateHandler, timeHandler };